package com.thjk.bdf.preloan.web.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.thjk.bdf.common.utils.BeanUtil;
import com.thjk.bdf.preloan.web.request.CustInfo;
import com.thjk.bdf.preloan.web.util.SeesionUtils;

@Component
public class SessionInterptor implements HandlerInterceptor{
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Value("${unifyacct.customerInfo.url}")
	private String unifyacctCustomerInfoUrl;
	
	@Value("${login.url}")
	private String loginUrl;
	
	@Autowired
	private RestTemplate restTemplate;
	
	private String errorUrl = "/error";
	
	private String PRODUCT_INDEX="/bdfpreloan/bdfLoanProduct";
	
	/**
	 * 视图渲染之后的操作
	 */
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		SeesionUtils.clearData();
	}

	/**
	 * 处理请求完成后视图渲染之前的处理操作
	 * 404和500处理
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception {
		logger.info("-----在视图被渲染之前过滤404和500错误-----");
        if(response.getStatus()==500){
            modelAndView.setViewName("common/error");
        }else if(response.getStatus()==404){
            modelAndView.setViewName("common/error");
        }
	}

	/**
	 * 进入controller层之前拦截请求
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		logger.info("--------preHandle---------");
		try {
			JSONObject retStr = null;
			String ticket = request.getParameter("ticket");
			String url = request.getRequestURI();
			MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
			params.add("channel", "100010711");
			if (StringUtils.isNotBlank(ticket)) {
				params.add("ticket", ticket);
				retStr = restTemplate.postForObject(unifyacctCustomerInfoUrl, params, JSONObject.class);
			} else {
				String token = getTokenFromCookie(request);
				params.add("token", token);
				retStr = restTemplate.postForObject(unifyacctCustomerInfoUrl, params, JSONObject.class);
			}
			logger.info("---查询统一账户参数{}",params);
			logger.info("----------调用统一账户返回{}---------------", retStr);
			if (null == retStr) {
				logger.info("统一账户系统异常");
				request.getRequestDispatcher(errorUrl).forward(request,response);
				return false;
			}
			if (!"AC-00000000".equals(retStr.get("resultCode"))&&!PRODUCT_INDEX.equals(url)) {
				response.sendRedirect(loginUrl);
				return false;
			}
			if ("0".equals(retStr.get("state"))&&!PRODUCT_INDEX.equals(url)) {
				response.sendRedirect(loginUrl);
				return false;
			}
			if (StringUtils.isNotBlank(ticket)) {
				Cookie cookie = new Cookie("token", retStr.getString("token"));
				response.addCookie(cookie);
			}
			SeesionUtils.setData(setCustInfo(retStr));
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	private String getTokenFromCookie(HttpServletRequest request) {
		String cacheKey = null;
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				logger.info("cookie值：{}", cookie.getName());
				if ("token".equals(cookie.getName())) {
					cacheKey = cookie.getValue();
				}
			}
		}
		return cacheKey;
	}
	
	/**
	 * 获取custInfo信息
	 * @param retStr
	 * @return
	 * @throws Exception
	 */
	private CustInfo setCustInfo(JSONObject retStr) throws Exception{
		Map<String, Object> custInfoMap = new HashMap<String, Object>();
		custInfoMap.put("custId", retStr.get("custId"));//客户id
		custInfoMap.put("certNo", retStr.get("certNo"));//客户证件号
		custInfoMap.put("phone", retStr.get("phone"));//手机号
		custInfoMap.put("name", retStr.get("name"));//姓名
		custInfoMap.put("loginSerId", retStr.get("loginSerId"));//行为流水号
		CustInfo info = new CustInfo();
		return (CustInfo) BeanUtil.mapToObject(custInfoMap, info.getClass());
	}
	
}
